<template>
  <div class="drawing-container">
    <div id="tui-image-editor"></div>
    <button @click="save" class="btn">保存</button>
  </div>
</template>
<script>
import "tui-image-editor/dist/tui-image-editor.css";
import "tui-color-picker/dist/tui-color-picker.css";
import ImageEditor from "tui-image-editor";
import { zh } from "../../src/lang/zh";
import { customTheme } from "../../src/components/customTheme ";
import img from "../../public/init.png";

export default {
  data() {
    return {
      instance: null,
      formData: null,
    };
  },
  mounted() {
    this.init();
  },

  methods: {
    init() {
      const tuiImageEditor = document.querySelector("#tui-image-editor");

      this.instance = new ImageEditor(tuiImageEditor, {
        includeUI: {
          loadImage: {
            path: img,
            name: "image",
          },

          menuBarPosition: "top", // 菜单所在的位置
          locale: zh, // 本地化语言为中文
          theme: customTheme,
        },
        cssMaxWidth: 800, //宽
        cssMaxHeight: 500, //高
      });
      document.getElementsByClassName("tui-image-editor-main")[0].style.top =
        "45px"; // 图片距顶部工具栏的距离
    },

    save() {
      const base64String = this.instance.toDataURL(); // base64 文件
      const data = window.atob(base64String.split(",")[1]);
      const ia = new Uint8Array(data.length);
      for (let i = 0; i < data.length; i++) {
        ia[i] = data.charCodeAt(i);
      }
      const blob = new Blob([ia], { type: "image/png" }); // blob 文件
      const form = new FormData();
      form.append("image", blob);
      this.$emit("upload", form);
    },
  },
};
</script>

<style>
.drawing-container {
  width: 900px;
  height: 700px;
  position: relative;
}

.tui-image-editor-container .tui-image-editor-help-menu.top {
  left: 60%;
  transform: translateX(-75%);
}

.btn {
  position: absolute;
  top: 8px;
  z-index: 999;
  right: 20px;
  background: #feba3b;
  border: none;
  color: #fff;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  border-radius: 20px;
  width: 120px;
  height: 40px;
}

.tui-image-editor-container .tui-image-editor-header-logo {
  display: none;
}
</style>
